package cn.cdut.yiwenqian.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
 * 楠岃瘉鐮佺敓鎴愮被
 * 鐢ㄤ簬鐢熸垚鐢ㄦ埛鐧诲綍鏃堕渶瑕佽緭鍏ョ殑楠岃瘉鐮�
 * @author yitek
 *
 */
public class RandomCodeServlet extends HttpServlet{
	/**
	 * 鍥剧墖瀹藉害
	 */
	private int width=60;
	/**
	 * 鍥剧墖楂樺害
	 */
	private int height=20;
	/**
	 * 鐢熸垚楠岃瘉鐮佹墽琛屾柟娉�
	 */
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		BufferedImage image=new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics2D g=image.createGraphics();
		
		
		Random random=new Random();
		g.setColor(getColor(200,250));
		g.fillRect(0, 0, width, height);
		
		Font font=new Font("Times New Roman", Font.PLAIN, 18);
		g.setFont(font);
		g.setColor(new Color(255,255,255));
		g.drawRect(0, 0, width-1, height-1);
		g.setColor(getColor(160,200));
	
		for (int i = 0; i < 155; i++) {
			int x=random.nextInt(width);
			int y=random.nextInt(height);
			int x1=random.nextInt(12);
			int y1=random.nextInt(12);
			g.drawLine(x, y, x+x1, y+y1);
		}
		
		
		StringBuffer randomCode=new StringBuffer();
		int red=0;
		int green =0;
		int blue=0;
		for (int i = 0; i < 4; i++) {
			String strRand=String.valueOf(random.nextInt(10));
			red = 20+random.nextInt(110);
            green =20+ random.nextInt(50);
            blue =20+ random.nextInt(50);
            g.setColor(new Color(red,green,blue));
            g.drawString(strRand,13*i+6, 16);
            randomCode.append(strRand);
		}
		HttpSession session=req.getSession();
		session.setAttribute("rand", randomCode.toString());
	
		res.setHeader("Pragma","no-cache");
		res.setHeader("Cache-Control", "no-cache");
		res.setDateHeader("Expire",0);
		res.setContentType("image/jpeg");
		g.dispose();
		ServletOutputStream sos=res.getOutputStream();
		ImageIO.write(image, "jpeg",sos);
		
	}
	/**
	 * 鍙栧緱棰滆壊鏁版嵁
	 * @param a
	 * @param b
	 * @return
	 */
	public Color getColor(int a,int b){
		
		Random random=new Random();
		if (a>255){
			a=255;
		}
		if(b>255){
			b=255;
		}
		int c=a+random.nextInt(b-a);
		int d=a+random.nextInt(b-a);
		int e=a+random.nextInt(b-a);
		return new Color(c,d,e);
		
		
	}
	
}
